package dnl.utils.jdbc.impexp;

import com.thoughtworks.xstream.XStream;
import dnl.persistence.TableInfo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Daniel Orr
 */
public class MetadataRegistry {

    private Map<String, TableInfo> sourceTableInfos = new HashMap<>();

    private static final XStream xStream = new XStream();

    File exportDir;

    public File getExportDir() {
        return exportDir;
    }

    public void setExportDir(File exportDir) {
        this.exportDir = exportDir;
    }

    public void addSourceTableInfo(TableInfo ti) {
        sourceTableInfos.put(ti.getTableName(), ti);
    }

    public TableInfo getTableInfo(String tableName) {
        return sourceTableInfos.get(tableName);
    }

    public Set<String> getTableNames() {
        return sourceTableInfos.keySet();
    }

    public File getFileForTable(String tableName) {
        if (sourceTableInfos.get(tableName) == null || exportDir == null) {
            return null;
        }
        return new File(exportDir, tableName+".csv");
    }

    public static void persistToFile(MetadataRegistry metadataRegistry, File f) {
        File target = f;
        if (f.isDirectory()) {
            target = new File(f, "metadata.xml");
        }
        synchronized (xStream) {
            try {
                xStream.toXML(metadataRegistry, new BufferedWriter(new FileWriter(target)));
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    public static MetadataRegistry fromFile(File f) {
        File target = f;
        if (f.isDirectory()) {
            target = new File(f, "metadata.xml");
        }
        synchronized (xStream) {
            final MetadataRegistry metadataRegistry = (MetadataRegistry) xStream.fromXML(target);
            metadataRegistry.setExportDir(target.getParentFile());
            return metadataRegistry;
        }
    }
}
